import React, { Component } from "react";
import { Platform, PermissionsAndroid } from "react-native";
// import { connect } from "react-redux";

// import { Button, WingBlank, WhiteSpace, Toast } from "@ant-design/react-native";
import { Toast, WhiteSpace } from "@ant-design/react-native";

import Sound from "react-native-sound"; // 播放声音组件
import { AudioRecorder, AudioUtils } from "react-native-audio";
import { getUUID } from "utils";
// import NavBar from "./NavBar";
// let audioPath = AudioUtils.DocumentDirectoryPath + '/test.aac';
// 目录/data/user/0/com.opms_rn/files/test.aac

class AudioRecord extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentTime: 0.0, // 开始录音到现在的持续时间
      recording: false, // 是否正在录音
      stoppedRecording: false, // 是否停止了录音
      // finished: false, // 是否完成录音
      audioPath: `${AudioUtils.DocumentDirectoryPath}/test.aac`, // 路径下的文件名
      hasPermission: undefined, // 是否获取权限
    };
  }

  componentDidMount() {
    // 页面加载完成后获取权限
    this.checkPermission().then(hasPermission => {
      this.setState({ hasPermission });

      // 如果未授权, 则执行下面的代码
      if (!hasPermission) return;
      this.prepareRecordingPath();

      AudioRecorder.onProgress = data => {
        this.setState({ currentTime: Math.floor(data.currentTime) });
      };

      AudioRecorder.onFinished = data => {
          this.finishRecording(data.status === "OK", data.audioFileURL);
      };
    });
    // console.log(this.props.navigator)
    // console.log(audioPath)
  }

  // 执行录音的方法
  prepareRecordingPath = () => {
    // 创建新文件
    let audioPath = getUUID();
    // 路径下的文件名
    audioPath = `${AudioUtils.DocumentDirectoryPath}/test_${audioPath}.aac`;
    this.setState({ audioPath });
    AudioRecorder.prepareRecordingAtPath(audioPath, {
        SampleRate: 8000,
      Channels: 1,
      AudioQuality: "Low", // 录音质量
      AudioEncoding: "aac", // 录音格式
      AudioEncodingBitRate: 32000, // 比特率
    });
  };

  // 检测是否授权
  checkPermission = () => {
    if (Platform.OS !== "android") {
      return Promise.resolve(true);
    }

    const rationale = {
      title: "获取录音权限",
      message: "正请求获取麦克风权限用于录音,是否准许",
    };

    return PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
      rationale
    ).then(result => {
      // alert(result);     //结果: granted ,    PermissionsAndroid.RESULTS.GRANTED 也等于 granted
      return result === true || PermissionsAndroid.RESULTS.GRANTED;
    });
  };

  upload = () => {
    const { dispatch } = this.props;
    const { audioPath } = this.state;
    const form = new FormData();

    form.append("file", {
      file: `file://${audioPath}`,
      type: "audio/aac",
      name: `test_${Date.now()}.aac`,
    });

    // Promise.once(resolve => {

    // });
    dispatch({
      type: "home/uploadAudio",
      payload: { form },
    }).then(res => {
      if (res !== null) {
        // resolve(null);
        Toast.success("上传成功", 1);
      }
    });
  };

  stopBtn = () => {
    this.stop();
  };

  playBtn = () => {
    this.play();
  };

  finishRecording = (didSucceed, filePath) => {
    const { currentTime } = this.state;
    // this.setState({ finished: didSucceed });
    // eslint-disable-next-line no-console
    console.log(
      `Finished recording of duration ${currentTime} seconds at path: ${filePath}`
    );
  };

  record = async () => {
    // 如果正在录音
    const {
      recording,
      hasPermission,
      stoppedRecording,
      audioPath,
    } = this.state;
    if (recording) {
      alert("正在录音中!");
      return;
    }

    // 如果没有获取权限
    if (!hasPermission) {
      alert("没有获取录音权限!");
      return;
    }

    // 如果暂停获取停止了录音
    if (stoppedRecording) {
      this.prepareRecordingPath(audioPath);
    }

    this.setState({ recording: true });

    try {
      await AudioRecorder.startRecording();
      // const filePath = await AudioRecorder.startRecording();
    } catch (error) {
      // eslint-disable-next-line no-console
      console.error(error);
    }
  };

  stop = async () => {
    // 如果没有在录音
    const { recording } = this.state;
    if (!recording) {
      alert("没有录音, 无需停止!");
      return;
    }

    this.setState({ stoppedRecording: true, recording: false });

    try {
      const filePath = await AudioRecorder.stopRecording();

        // if (Platform.OS === "android") {
        //   if (typeof this.finishRecording === "function") {
        //     this.finishRecording(true, filePath);
        //   }
        // }
        const pcmPath = `${AudioUtils.DocumentDirectoryPath}/test.pcm`;
        console.log(pcmPath);
        return {filePath, pcmPath};
    } catch (error) {
      // eslint-disable-next-line no-console
      console.error(error);
      return null;
    }
  };

  play = async () => {
    // 如果在录音 , 执行停止按钮
    const { recording, audioPath } = this.state;
    if (recording) {
      await this.stop();
    }

    // 使用 setTimeout 是因为, 为避免发生一些问题 react-native-sound中
    setTimeout(() => {
      const sound = new Sound(audioPath, "", error => {
        if (error) {
          // eslint-disable-next-line no-console
          console.log("failed to load the sound", error);
        }
      });

      setTimeout(() => {
        sound.play(success => {
          if (success) {
            // eslint-disable-next-line no-console
            console.log("successfully finished playing");
          } else {
            // eslint-disable-next-line no-console
            console.log("playback failed due to audio decoding errors");
          }
        });
      }, 100);
    }, 100);
  };

  render() {
    return <WhiteSpace />;
  }
}

export default AudioRecord;
